
// 继承自Menu_A
var Menu_B = function(w, h, length){
    this.data = [];
    w && (this.w = w);
    h && (this.h = h);
    length && (this.length = length);
}

Menu_B.prototype = $.extend(new Menu_A(), {
    pgn: 50,
    bufferPage: 0, //前后缓冲页数
    //异步循环
    loop: function(fn, min, max, callback){
        var i = min;
        var a = function(){
            if (i > max) {
                callback && callback();
                return;
            }
            //common.log("i= " + i);
            i++
            fn(a);
        }
        a();
    },
    //将数据存入菜单data节点
    setData: function(d){
        if (d && d.sti >= 0 && d.length >= 0 && $.isArray(d.data)) {
            this.length = d.length;
            var data = d.data;
            for (var i = 0; i < data.length; i++) {
                this.data[i + d.sti] = data[i];
            }
            //common.log("setData: " + d.sti + " - " + (d.sti + d.data.length - 1));
            this.z() == this.z(d.sti) && this.onCurrentDataUpdate && this.onCurrentDataUpdate();
            return true;
        }
        return false;
    },
    
    //
    checkCurrPage: function(callback){
        var p = this.z(this.i);
        var ppn = this.p();
        var self = this;
        if (this.data[ppn * p] == null && this.onLack) {
            this.onLack(p, ppn, function(){
                (self.bufferPage > 0) && self.checkBuffPage();
                callback && callback();
            })
            return false;
        }
        callback && callback();
        return true;
    },
    checkBuffPage: function(callback){
        var p = this.z(this.i);
        var max = this.z(this.length - 1) + 1;
        var ppn = this.p();
        var data = this.data;
        var r = []
        
        //如果缓冲超过页数的一半，则最多缓冲全部页
        var t = max - 1 > this.bufferPage * 2 ? this.bufferPage * 2 : max - 1;
        for (var i = 1; i <= t; i++) {
            var n = this.rmd(p - Math.pow(-1, i) * Math.ceil(i / 2), max);
            
            //common.log(i,n);	
            //检验每页开头是否为空，为空则需要取数据
            if (data[ppn * n] == null) {
                r.push(n)
            }
        }
        //common.log(p, r)
        
        //通过生成的r，进行异步循环
        if (r.length) {
            var self = this;
            var j = 0;
            this.loop(function(cb){
                self.onLack && self.onLack(r[j], ppn, function(){
                    //common.log(r[j])
                    j++;
                    cb && cb();
                })
            }, 0, r.length - 1, callback)
            //this.onLack && this.onLack(ppn, r, callback);
            return false;
        }
        callback && callback();
        return true;
    },
    
    
    
    
    //缺失数据，需要加载，传入每页条数和页数数组
    onLack: function(pgn, page, callback){
    },
    //当前页数据被更新
    onCurrentDataUpdate: function(){
    }
});
